package xuegao.study.mall.admin.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import xuegao.study.mall.common.api.ResultCode;
import xuegao.study.mall.common.exception.ApiException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 此种限流的局限在于没有处理好单位时间内的大并发请求
 * 设定我们一分钟内限制100个请求,那假设在59秒的时候来了100个请求,可以正常接受。而在下一个1秒的时候又来了100个请求,那么这种恶意请求势必对系统造成伤害。
 * (临界点缺陷)
 */
@Component
public class IpLimitInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(IpLimitInterceptor.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        HandlerMethod handlerMethod;
        try {
            handlerMethod = (HandlerMethod)handler;
        } catch (Exception e) {
            logger.error("ip limit interceptor error", e);
            throw new ApiException(ResultCode.FAILED);
        }
        // 获取类和方法上面的注解
        IpLimit ipLimit = handlerMethod.getMethod().getAnnotation(IpLimit.class);
        if (ipLimit == null) {
            ipLimit = handlerMethod.getBeanType().getAnnotation(IpLimit.class);
        }
        if (ipLimit == null) {
            return true;
        }
        String remoteIp = request.getRemoteAddr();
        String key = handlerMethod.getMethod().getName() + ":" + remoteIp;
        Object valueObj = redisTemplate.opsForValue().get(key);
        String value = "0";
        if (valueObj != null) {
            value = String.valueOf(valueObj);
        }
        int count = ipLimit.count();
        if (StringUtils.hasText(value) && Integer.parseInt(value) > count) {
            logger.warn("ip limit interceptor limit req, ip:{}", remoteIp);
            throw new ApiException(ResultCode.IP_FLOW_LIMIT);
        } else {
            if (StringUtils.hasText(value)) {
                redisTemplate.opsForValue().set(key, Integer.parseInt(value) + 1, 10, TimeUnit.SECONDS);
            } else {
                redisTemplate.opsForValue().set(key, 1, 10, TimeUnit.SECONDS);
            }
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
